<template>
  <div
    v-toggle-full="resetTableWidth"
    element-loading-background="rgba(255, 255, 255, 0.8)"
    class="base-dialog"
    :append-to-body="true"
    destroy-on-close
    align="center"
    :custom-class="customClass"
  >
    <div>
      <el-container class="record-edit-form-container">
        <el-aside width="278px" class="record-edit-form-container_aside">
          <ElnTemplateSide
            ref="ElnTemplateSide"
            :form-data="formData"
            :page-view-mode="pageViewMode"
            :readonly="readonly"
            :detection-state="detectionState"
          />
        </el-aside>
        <el-main class="record-edit-form-container_main">
          <div
            v-for="item in targetList"
            :key="item.id"
            class="target-card-item"
            :class="{ readonly: readonly }"
            :style="{ width: item.span === 12 ? '50%' : '100%' }"
          >
            <component
              :is="item.name"
              :ref="item.name"
              class="card-item"
              :params="item"
              :page-view-mode="pageViewMode"
              :readonly="readonly"
            ></component>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>
<script>
import {
  getSingleList,
  update,
  verify,
} from "../AuditComponents/api/ExperimentTemplateRecord.js";
import { deepClone } from "@/utils";
import print from "@/ModuleEln/ModuleEln/img/print.png";
import download from "@/ModuleEln/ModuleEln/img/download.png";
// 引入组件
import ElnTemplateSide from "@/ModuleEln/ModuleEln/views/ModuleEln/Components/ElnTemplateSide.vue";
const allComponents = require.context(
  "@/ModuleEln/ModuleEln/components/BaseControl",
  true,
  /\.vue$/
);
const res_components = {};
allComponents.keys().forEach((item) => {
  const comp = allComponents(item);
  const name = comp.default.name;
  res_components[name] = comp.default;
});
export default {
  name: "AuditExperimentTemplateRecordVerify",
  components: { ...res_components, ElnTemplateSide },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
    row: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      title: "",
      customClass: "panna-dialog_big",
      pageViewMode: "runtime",
      readonly: true,
      detectionState: false,
      formLabelWidth: "70px",
      showPdf: false,
      print,
      download,
      loading: false,
      loadText: "",
      reviewerList: [],
      targetList: [],
      leftData: [],
      defaultValueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "DatePicker",
      ],
      valueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "Image",
      ],
      formData: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: "",
        templateContentDto: { leftData: [], centerData: [] },
      },
      errorMsg: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: "",
      },
    };
  },
  watch: {
    editId: {
      handler() {
        if (this.editId) {
          this.init();
        }
      },
      immediate: true,
    },
  },
  methods: {
    async init() {
      if (this.editId) {
        await this.getDataInfo();
      }

      if (!this.formData.templateContentDto) return;
      this.title = this.formData.templateName;
      this.leftData = this.formData.templateContentDto.leftData;
      // let isExisTable = false;
      this.targetList = this.formData.templateContentDto.centerData.filter(
        (x) => {
          // if (x.controlType === "Table") {
          //   if (isExisTable) return false;
          //   else {
          //     isExisTable = true;
          //     return true;
          //   }
          // }
          return x && x.controlType !== "Title";
        }
      );
      try {
        this.targetList.forEach((item) => {
          item.name = `Control${item.controlType}`;
          if (item.value && this.valueJSONType.includes(item.controlType)) {
            item.value = JSON.parse(item.value);
          }
          if (
            item.defaultValue &&
            this.defaultValueJSONType.includes(item.controlType)
          ) {
            item.defaultValue = JSON.parse(item.defaultValue);
          }
        });
      } catch (e) {
        console.log(e);
      }
      this.formData.templateContentDto.leftData.forEach((left) => {
        switch (left.code) {
          case "templateCode":
            this.formData["experimentNumber"] = left.value;
            break;
          // case "sampleCategoryName":
          //   this.formData.experimentSampleCategorys = left.data || "";
          //   try {
          //     this.formData.sampleCategoryName =
          //       JSON.parse(left.value)[0] || "";
          //   } catch (e) {
          //     this.formData.sampleCategoryName = left.value;
          //   }
          //   break;
          case "articleNumber":
            this.formData[left.code] = left.value;
            break;
          case "creatorName":
            this.formData[left.code] =
              this.formData.testerId.filter((item) => item !== "0") || [];
            break;
          case "creatorTime":
            this.formData[left.code] = left.value;
            break;
          default:
            break;
        }
      });
    },
    getDataInfo() {
      return new Promise((resolve, reject) => {
        getSingleList({ id: this.editId })
          .then((res) => {
            this.formData = res.data;
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    save(type) {
      if (!type) {
        this.handleClose();
        return;
      }
      this.$refs.formData.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const saveList = new Array(this.targetList.length).fill(null);
        const promiseTable = [];
        for (const i in this.$refs) {
          if (i === "formData") continue;
          const tempRef = this.$refs[i];
          if (!Array.isArray(tempRef) || !tempRef.length) continue;
          tempRef.forEach((ref) => {
            if (ref.validate instanceof Function) {
              const refData = ref.validate();
              if (refData instanceof Promise) {
                promiseTable.push(refData);
                return;
              }
              const controlValue = deepClone(refData);
              // 删除多余的参数
              delete controlValue.design;
              delete controlValue.name;
              // 修改特定控件value&defaultValue数据格式
              controlValue.data = controlValue.data.filter(
                (x) => x.label !== ""
              );
              // 格式化特殊控件的value以及defaultValue值
              controlValue.value &&
                this.valueJSONType.includes(controlValue.controlType) &&
                (controlValue.value = JSON.stringify(controlValue.value));
              controlValue.defaultValue &&
                this.defaultValueJSONType.includes(controlValue.controlType) &&
                (controlValue.defaultValue = JSON.stringify(
                  controlValue.defaultValue
                ));
              const currentIdx = this.targetList.findIndex(
                (x) => x.id === controlValue.id
              );
              saveList.splice(currentIdx, 1, controlValue);
            }
          });
        }
        // 处理table的异步数据问题
        if (promiseTable.length) {
          const tableData = await Promise.all(promiseTable);
          tableData.forEach((x) => {
            const { controlValue } = deepClone(x);
            const currentIdx = this.targetList.findIndex(
              (v) => v.id === controlValue.id
            );
            controlValue.value &&
              (controlValue.value = JSON.stringify(controlValue.value));
            controlValue.defaultValue &&
              (controlValue.defaultValue = JSON.stringify(
                controlValue.defaultValue
              ));
            saveList.splice(currentIdx, 1, controlValue);
          });
          console.log(saveList);
        }
        // 转换为样品类别字段的name值
        // this.formData.sampleCategoryName =
        //   this.formData.experimentSampleCategorys.find(
        //     (x) => x.id === this.formData.sampleCategoryName
        //   ).name;
        // 根据code从formData去除最新的value值
        this.leftData.forEach((left) => {
          if (Object.prototype.hasOwnProperty.call(this.formData, left.code)) {
            left.value = this.formData[left.code];
          }
        });
        const params = deepClone(this.formData);
        params.templateContentDto = {
          leftData: this.leftData,
          centerData: saveList,
        };
        update(params).then((res) => {
          this.handleClose();
          this.$parent.getList();
        });
      });
    },
    resetTableWidth() {
      this.$refs.ControlTable?.length &&
        this.$refs.ControlTable.forEach((x) => {
          x.customFn();
        });
    },
    handleClose() {
      this.$emit("update:dialogFormVisible", false);
    },
    innerVerify(obj, status) {
      verify({
        id: obj.auditDataId,
        _id: this.formData._id,
        status: status,
        remark: obj.remark,
        dataGroup: obj.dataGroup,
        creatorId: this.formData.creatorId,
      })
        .then((res) => {
          this.$emit("passOrNoPassEmit");
        })
        .catch();
    },
    innerPass(obj) {
      const _this = this;
      _this.innerVerify(obj, 30);
    },
    innerReject(obj) {
      const _this = this;
      _this.innerVerify(obj, 40);
    },
    innerWithdraw(obj) {
      // invalid({
      //   _id: this.formData._id,
      //   dataGroup: obj.dataGroup,
      //   invalidRason: obj.remark,
      // })
      //   .then((res) => {
      //     this.$emit("passOrNoPassEmit");
      //   })
      //   .catch();
      const _this = this;
      _this.innerVerify(obj, 60);
    },
  },
};
</script>
<style lang="scss" scoped>
.Eln_flex {
  display: flex;
  align-items: center;
  align-content: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
}

.el-container.record-edit-form-container {
  height: 100%;

  .record-edit-form-container_aside {
    box-sizing: border-box;
    padding: 24px;
    background-color: #ecf0f7;
    overflow: hidden;
    overflow-y: auto;

    & > .system-user-form {
      .el-form-item {
        .el-form-item__label {
          height: 16px;
          font-size: 12px;
          font-family: "Microsoft YaHei";
          color: #666666;
          line-height: 16px;
          margin-top: 9px;
        }

        .el-date-editor > .el-input__inner {
          // border: none;
          padding-right: 15px;
        }
      }
    }
  }

  .record-edit-form-container_main {
    @extend .Eln_flex;
    padding: 0 16px;
    min-height: 600px;
    padding-bottom: 18px;
    @extend .Eln_flex;
    justify-content: flex-start;
    overflow: auto;

    & > .target-card-item {
      margin-top: 18px;

      // 各控件基础样式
      .control {
        display: flex;
        align-items: center;
        box-sizing: border-box;

        &.flex-start {
          align-items: flex-start;
        }
        &.image {
          align-items: flex-start;

          & > .control-title {
            margin-top: 6px;
          }

          & > .control-operate {
            margin-top: 4px;
          }
        }

        & > * {
          flex-shrink: 0;
        }

        ::v-deep .control-title {
          height: 16px;
          font-size: 12px;
          font-family: "Microsoft YaHei";
          color: #666666;
          line-height: 16px;
          display: flex;
          align-items: center;
          justify-content: flex-end;

          & > .title-icon {
            color: red;
          }

          & > .title-label {
            text-align: right;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        ::v-deep .control-content {
          flex: 1;
          margin-right: 52px;
          margin-left: 10px;
        }
      }

      &.readonly {
        .card-item.control {
          min-height: 29px;

          &:hover {
            & > .control-operate {
              display: block;
            }
          }

          ::v-deep .control-content {
            .el-input .el-input__inner,
            .el-textarea .el-textarea__inner {
              border-color: #dcdfe6 !important;
            }

            .el-input.el-date-editor {
              width: 100%;
            }

            .el-select {
              .el-select__tags {
                height: auto;
                .el-tag__close {
                  display: none;
                }
              }
            }
          }

          & > .control-operate {
            display: none;
          }
        }
      }

      &.preview {
        cursor: default !important;

        .control-content {
          flex: 1;

          & > .el-select {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
